iT邦幫忙

2025 iThome 鐵人賽

DAY 21
0
生成式 AI

Swift一下就會了系列 第 21

Day 21 留言板 6

  • 分享至 

  • xImage
  •  

送出留言

當使用者輸入姓名與留言後,按下送出即可將訊息存入資料庫並顯示在畫面上。

// 送出按鈕
    @IBAction func btnSentAciton(_ sender: Any){
        let realm = try! Realm()
        
        if btnSent.currentTitle == "送出" {
            
            if let user = txfUser.text, let message = txvContent.text {
                
                if !user.isEmpty && !message.isEmpty {
                    
                    let currentTime = getSystemTime()
                    
                    let newMessage = MessageBoard(name: user, content: message, currentTime: currentTime)
                    
                    try! realm.write {
                        
                        realm.add(newMessage)
                        // 如果isAscending是true(升序),就加到陣列的最後面,就是由舊到新的概念
                        if isAscending {
                            messageArray.append(newMessage)
                            
                            // 如果是false(由新到舊),就放到陣列的最前面
                        } else {
                            messageArray.insert(newMessage, at: 0)
                        }
                        
                        tbvData.reloadData()

                        txfUser.text = ""
                        txvContent.text = ""
                    }
                    print("Added new message with time: \(currentTime)")
                } else {
                    showAlert(message: "請輸入使用者名稱和內容")
                }
            }
        }
    }

Tips:

  • 輸入檢查:確保 usermessage 不為空。
  • 時間戳記:getSystemTime() 取得當下時間,存入資料庫。
  • 排序邏輯:
    isAscending = true → 舊到新:新增訊息加到最後。
    isAscending = false → 新到舊:新增訊息插到最前。
  • UI 即時更新:tbvData.reloadData() 重新載入 TableView
  • 清空輸入框:送出後清空使用者與內容欄位。

排序按鈕

除了送出留言,我們也希望使用者可以隨時切換留言的時間排序。
觸發排序選單

    //觸發排序選單
    @IBAction func btnSortSection(_ sender: Any) {
        showSortOptions()
    }

排序選單的實作:

    // 排序按鈕
    func showSortOptions() {
        // 警告彈窗
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        // 越上面訊息越晚
        let ascendingAction = UIAlertAction(title: "舊到新", style: .default) { [weak self] _ in
            // 改變追蹤排序的變數
            self?.isAscending = true
            // 利用前面改變的追蹤的變數做排序
            self?.sortMessages()
            // 刷新頁面
            self?.tbvData.reloadData()
        }
        
        // 越上面訊息越早
        let descendingAction = UIAlertAction(title: "新到舊", style: .default) { [weak self] _ in
            
            self?.isAscending = false
            
            self?.sortMessages()
            
            self?.tbvData.reloadData()
        }
        
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        // 將上面的選項加入最開始命名的空的警告彈窗
        alertController.addAction(ascendingAction)
        alertController.addAction(descendingAction)
        alertController.addAction(cancelAction)
        
        // 這裡是設定彈出視窗是要從排序按鈕按才會彈出來
        if let popoverController = alertController.popoverPresentationController {
            popoverController.sourceView = btnSort
            popoverController.sourceRect = btnSort.bounds
        }
        
        // 呼叫出alerController
        present(alertController, animated: true, completion: nil)
    }

結語

今天我們完成了 留言新增排序切換 功能。


上一篇
Day 20 留言板 5
系列文
Swift一下就會了21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言